<?php
use app\admin\model\Attachment;
use LhpAmis\Renderers\BaseApi;
use LhpAmis\Renderers\BaseRenderer;
use LhpAmis\util\AmisBaseApi;
use app\common\service\AuthService;

if (!function_exists('authAmis')) {
    /**
     * 验证权限 自行实现AmisUserAuth函数
     * @param mixed $actionOrUrl
     * @return bool
     */
    function authAmis($actionOrUrl)
    {
        return true;
        if (is_object($actionOrUrl) && $actionOrUrl instanceof BaseRenderer) {

            $node = extractUrlsFromJson($actionOrUrl);
            if (empty($node)) {
                return false;
            }
            return function_exists('AmisUserAuth') ? AmisUserAuth($node[0]) : true;

        } else {
            return false;
        }
    }
    function extractUrlsFromJson($data = [])
    {
        // 将数据转换为字符串以便进行正则匹配
        $dataString = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        // 正则表达式匹配URL路径
        $pattern = '/https?:\/\/[^\s"]+|[a-zA-Z0-9\-._~:\/?#\[\]@!$&\'()*+,;=]+\/[^\s"]*/';
        preg_match_all($pattern, $dataString, $matches);

        // 返回匹配到的URL路径数组
        return $matches[0];
    }

}
// if (!function_exists('amis')) {
//     /**
//      * @param $type
//      *
//      * @return \LhpAmis\Renderers\Amis | \LhpAmis\Renderers\Component
//      */
//     function amis($type = null)
//     {
//         if (filled($type)) {
//             return \LhpAmis\Renderers\Component::make()->setType($type);
//         }

//         return \LhpAmis\Renderers\Amis::make();
//     }
// }

if (!function_exists('amisMake')) {
    /**
     * @return \LhpAmis\Renderers\Amis
     * @deprecated
     */
    function amisMake()
    {
        return \LhpAmis\Renderers\Amis::make();
    }
}
if (!function_exists('getUrlQuery')) {


    /**
     * 将参数变为字符串
     * @param $array_query
     * @return string
     */
    function getUrlQuery($array_query)
    {
        $tmp = array();
        foreach ($array_query as $k => $param) {
            $tmp[] = $k . '=' . $param;
        }
        $params = implode('&', $tmp);
        return $params;
    }
}
if (!function_exists('adminUrl')) {
    function adminUrl(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        $urlquery = '';
        if (!empty($vars)) {
            $urlquery = '?' . getUrlQuery($vars);
        }
        return (string) url($url, [], $suffix, $domain) . $urlquery;
    }
}
if (!function_exists('admin_url')) {
    function admin_url($path = null, $needPrefix = false)
    {
        $needPrefix = config('admin.route.needPrefix');

        if (!$needPrefix) {
            $prefix = '/' . config('admin.route.prefix');
        } else {
            $prefix = $needPrefix ? '/' . config('admin.route.prefix') : '';
        }

        return $prefix . '/' . trim($path, '/');
    }
}


if (!function_exists('BaseApiDelete')) {

    /**
     * 删除接口
     * @param string $thinkUrl thinkphp路由地址
     * @param array $query 请求参数
     * @param array $data  请求数据
     * @param mixed $type 提交类型：json   form-data    form
     * @return BaseApi
     */
    function BaseApiDelete(string $thinkUrl = '', array $query = [], $data = [], $type = 'form'): BaseApi
    {
        return AmisBaseApi::make()->amisBaseApi($thinkUrl, 'delete', $query, $data, $type);
    }
}
if (!function_exists('BaseApiPut')) {
    /**
     * 修改接口
     * @param string $thinkUrl thinkphp路由地址
     * @param array $query 请求参数
     * @param array $data  请求数据
     * @param mixed $type 提交类型：json   form-data    form
     * @return BaseApi
     */
    function BaseApiPut(string $thinkUrl = '', array $query = [], $data = [], $type = 'form'): BaseApi
    {
        return AmisBaseApi::make()->amisBaseApi($thinkUrl, 'put', $query, $data, $type);
    }
}
if (!function_exists('BaseApiPost')) {

    /**
     * 添加接口
     * @param string $thinkUrl thinkphp路由地址
     * @param array $query 请求参数
     * @param array $data  请求数据
     * @param mixed $type 提交类型：json   form-data    form
     * @return BaseApi
     */
    function BaseApiPost(string $thinkUrl = '', array $query = [], $data = [], $type = 'form'): BaseApi
    {
        return AmisBaseApi::make()->amisBaseApi($thinkUrl, 'post', $query, $data, $type);
    }
}
if (!function_exists('BaseApiGet')) {
    /**
     * 获取接口
     * @param string $thinkUrl thinkphp路由地址
     * @param array $query 请求参数
     * @param mixed $type 提交类型：json   form-data    form
     * @return BaseApi
     */
    function BaseApiGet(string $thinkUrl = '', array $query = [], $type = 'form'): BaseApi
    {
        return AmisBaseApi::make()->amisBaseApi($thinkUrl, 'get', $query, [], $type);
    }
}
if (!function_exists('BaseApi')) {
    /**
     * API接口
     * @param string $thinkUrl thinkphp路由地址
     * @param string $method 请求方法
     * @param array $query 请求参数
     * @param array $data  请求数据
     * @param mixed $type 提交类型：json   form-data    form
     * @return BaseApi
     */
    function amisBaseApi(string $thinkUrl = '', string $method = 'post', array $query = [], $data = [], $type = 'form'): BaseApi
    {
        return AmisBaseApi::make()->amisBaseApi($thinkUrl, $method, $query, $data, $type);
    }

}

if (!function_exists('getDomain')) {
    function getDomain()
    {
        $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
        return $scheme . "://" . $_SERVER['HTTP_HOST'];
    }
}

if (!function_exists('AmisUserAuth')) {
    /**
     * 验证权限 自行实现覆盖此函数
     * @param mixed $actionOrUrl
     * @return bool
     */
    function AmisUserAuth($url)
    {
        $adminId = (new \app\common\support\Token())->withRequestToken()->getClaim('admin_id') ?? '';
        $requestMethod = request()->method() ?? '';
        if (!\tauthz\facade\Enforcer::enforce($adminId, $url, $requestMethod)) {
            return false;
        }
        return true;
    }
}

if (!function_exists('lineToHump')) {

    /**
     * 下划线转驼峰
     * @param $str
     * @return null|string|string[]
     */
    function lineToHump($str)
    {
        $str = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
            return strtoupper($matches[2]);
        }, $str);
        return $str;
    }
}
if (!function_exists('humpToLine')) {

    /**
     * 驼峰转下划线
     * @param $str
     * @return null|string|string[]
     */
    function humpToLine($str)
    {
        $str = preg_replace_callback('/([A-Z]{1})/', function ($matches) {
            return '_' . strtolower($matches[0]);
        }, $str);
        return $str;
    }
}
if (!function_exists('getRealIp')) {

    /**
     * 获取真实IP
     * @return mixed
     */
    function getRealIp()
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
            foreach ($matches[0] as $xip) {
                if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                    $ip = $xip;
                    break;
                }
            }
        } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) {
            $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
        } elseif (isset($_SERVER['HTTP_X_REAL_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_IP'])) {
            $ip = $_SERVER['HTTP_X_REAL_IP'];
        }
        return $ip;
    }
}
if (!function_exists('readDirAllFiles')) {

    /**
     * 读取文件夹下的所有文件
     * @param $path
     * @param $basePath
     * @return array|mixed
     */
    function readDirAllFiles($path, $basePath = '')
    {
        list($list, $temp_list) = [[], scandir($path)];
        empty($basePath) && $basePath = $path;
        foreach ($temp_list as $file) {
            if ($file != ".." && $file != ".") {
                if (is_dir($path . DIRECTORY_SEPARATOR . $file)) {
                    $childFiles = readDirAllFiles($path . DIRECTORY_SEPARATOR . $file, $basePath);
                    $list = array_merge($childFiles, $list);
                } else {
                    $filePath = $path . DIRECTORY_SEPARATOR . $file;
                    $fileName = str_replace($basePath . DIRECTORY_SEPARATOR, '', $filePath);
                    $list[$fileName] = $filePath;
                }
            }
        }
        return $list;
    }
}
if (!function_exists('replaceTemplate')) {

    /**
     * 模板值替换
     * @param $string
     * @param $array
     * @return mixed
     */
    function replaceTemplate($string, $array)
    {
        foreach ($array as $key => $val) {
            $string = str_replace("{{" . $key . "}}", $val, $string);
        }
        return $string;
    }
}
if (!function_exists('format_bytes')) {
    /**
     * 格式化字节大小
     * @param  number $size      字节数
     * @param  string $delimiter 数字和单位分隔符
     * @return string            格式化后的带单位的大小
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 5; $i++)
            $size /= 1024;
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('get_file_path')) {
    /**
     * 获取附件路径
     * @param int $id 附件id
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    function get_file_path($id = 0)
    {
        $path = Attachment::getFilePath($id);
        if (!$path) {
            return config('public_static_path').'admin/img/none.png';
        }
        return $path;
    }
}

if (!function_exists('get_files_path')) {
    /**
     * 批量获取附件路径
     * @param array $ids 附件id
     * @author 蔡伟明 <314013107@qq.com>
     * @return array
     */
    function get_files_path($ids = [])
    {
        $paths = model('admin/attachment')->getFilePath($ids);
        return !$paths ? [] : $paths;
    }
}